// tslint:disable
import { Component, Input, OnInit } from '@angular/core';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { EventService } from 'src/app/shared/service/event.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { ActionSheetService, Modal, ModalService } from 'ng-zorro-antd-mobile';
import { PageModalService } from "../../shared/service/page-modal-service";
import { ModalFromCenterLeave, ModalFromCenterEnter } from 'src/app/utils/transitions';
import { ActionSheetController, AlertController } from "@ionic/angular";
import { ModalController } from "@ionic/angular";
import { RemarksContentComponent } from "../remarks-content/remarks-content.component";
import { RecommendModalComponent } from '../recommend-modal/recommend-modal.component';
import { ShareService } from 'src/app/shared/service/share.service';
import { SharePageComponent } from '../share-page/share-page.component';
declare let $: any;
@Component({
  selector: 'app-employe-list',
  templateUrl: './employe-list.component.html',
  styleUrls: ['./employe-list.component.scss'],
})
export class EmployeListComponent implements OnInit {

  @Input() tagData: any;
  emptyDataHint = "暂无数据";
  showLoadMore = false;
  pageNo = 1;
  pageSize: number;
  pageTotal: number;
  listenerName: any;
  // 筛选及页面数据参数
  params: any = { content: {} };
  phoneArray = [];
  dataIndex: any;
  constructor(
    private appGlobalService: AppGlobalService,
    private actionSheetCtrl: ActionSheetController,
    private actionSheet: ActionSheetService, // 必须有
    private pageModalService: PageModalService, // 必须有
    private alertController: AlertController,
    private httpService: HttpService,
    private eventService: EventService,
    private shareService: ShareService,
    public modalController: ModalController
  ) {

  }
  ngOnChanges() {


    if (this.tagData && this.tagData.pageTotal) {
      console.log("ngOnChanges!!!!" + this.tagData.pageTotal);
      this.checkLoadMore()
    }
  }
  checkLoadMore() {
    this.pageTotal = this.tagData.pageTotal;
    this.pageNo = this.tagData.pageNo;
    this.pageSize = this.tagData.pageSize;
    this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize));
    if (this.tagData.hint !== undefined) {
      this.emptyDataHint = this.tagData.hint;
    }
  }
  ngOnInit() {

    // 蜂喔用户 1.9.18 新增
    this.listenerName = this.tagData.name + 'AskForList';
    this.eventService.eventEmit.on(this.listenerName, (obj) => {
      this.refreshListData(obj);
    });

    this.checkLoadMore();

    this.tagData.data.data.forEach(element => {

      if (element.secondBox
        && element.secondBox.billText
        && element.secondBox.billText.label) {

        element.secondBox.billText.textSplit = [];
        if (element.secondBox.billText.label.length > 0) {
          element.secondBox.billText.label.forEach(e => {
            element.secondBox.billText.textSplit.push(e.split('￥'));
          });
        }

      }
    })
  }

  moreClick(link) {
    if (link.type === 'tabClick') {
      if (link && link.params && link.params['tab_index']) {
        const tabIndex = parseInt(link.params['tab_index']);
        this.eventService.eventEmit.emit("topTabChangeByIndex", tabIndex);
        localStorage.setItem('subTab_index', link.params['subTab_index']);
      }
    } else {
      this.appGlobalService.openPage(link);
    }
  }
  itemClick(link, submit?) {
    // this.appGlobalService.openPage(link);
    if (link && submit !== undefined) {
      const params = {
        content: submit.params,
        id: submit.id,
        sessionId: localStorage.getItem('sessionId')
      };
      // 请求获取新数据
      this.httpService.post('application/submit', params, res => {
        // 请求数据成功
        if (res.success) {
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
      },
        err => {
          // 请求数据失败
          this.appGlobalService.showToast(err.message, 2000, 'middle');
        });
      this.pageModalService.openPage(link);
    } else {
      this.pageModalService.openPage(link);

    }

  }

  refreshListData(param) {
    const that = this;
    if (param === undefined) {
      return;
    }
    this.pageNo = 1;
    // if (!param.showName) {
    //   param.showName = this.tagData.data.submit.content.showName;
    // }
    this.params = { content: {} };
    this.params.content = param;
    this.params.id = this.tagData.data.submit.id;
    this.params.content.pageNo = this.pageNo;
    this.params.sessionId = localStorage.getItem("sessionId");
    this.httpService.post('application/submit', this.params, res => {
      if (res.success) {
        if (res.data.submit) {
          this.params = res.submit; // 为了每次刷新下一页的参数 "oldIndex"
        }
        this.tagData.data.data = [];
        const result = res.data.data; // JSON.parse(res.data.data);
        this.tagData.data.data = result;
        if (res.data.moreButton) {
          this.tagData.data.moreButton = res.data.moreButton;
        }
        if (res.data.submit && res.data.submit.content && res.data.submit.content.pageTotal) {
          this.pageTotal = res.data.submit.content.pageTotal;
          this.tagData.data.submit.content = res.data.submit.content;
          this.pageNo = 1;
        } else {
          this.pageTotal = this.tagData.pageTotal;
        }

        this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';

      } else {
        // 请求数据失败
        this.tagData.data.data = [];
        // this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    },
      err => {
        // 请求数据失败
        this.tagData.data.data = [];
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
      });
  }

  loadMoreData(event) {
    try {
      this.params = this.tagData.data.submit;
      this.pageNo = this.pageNo + 1;
      // // 参数
      this.params.content.pageNo = this.pageNo;
      this.params.id = this.tagData.data.submit.id;
      // 请求获取新数据
      this.params.sessionId = localStorage.getItem("sessionId");
      this.httpService.post('application/submit', this.params, res => {

        // 请求数据成功
        if (res.success) {
          if (res.data.submit) {
            this.params.content = res.data.submit.content; // 为了每次刷新下一页的参数 "oldIndex"
          }
          const resList = res.data.data;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(v => {
              this.tagData.data.data.push(v);
            });
          } else {
            event.target.disabled = true;
          }
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          // this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
        event.target.complete();

      }, err => {
        // 请求失败，更新当前页数
        this.pageNo = this.pageNo - 1;
        // 请求数据失败
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
        event.target.complete();

      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  remarkList2(more, item, dataIndex?) {
    const that = this;
    const buttons: any = [];
    if (more.childIconList) {
      more.listRemark = more.childIconList;
    } else {
      more['listRemark'] = more;
    }
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          // console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.selectItem(more, buttonIndex, item, dataIndex);
          }, 200);
        }
      }
    );
  }

  selectItem(item, index, currentItem, dataIndex?) {
    console.log('msg-----?', currentItem);
    const itemObj = item.listRemark[index];
    if (itemObj.modelType === 'dialog') {
      if (currentItem
        && currentItem.remarkButtons
        && currentItem.remarkButtons.iconList
        && currentItem.remarkButtons.iconList[0]) {
        const firstDialogBtn = currentItem.remarkButtons.iconList[0];
        if (itemObj.matchKey === firstDialogBtn.matchKey) {
          itemObj['formData'] = firstDialogBtn.formData;
        }
      }
      this.presentModal("remarks", itemObj);
    } else if (itemObj.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", itemObj);
    } else if (itemObj.modelType === 'iconLink') {
      // 修改 领取类型按钮
      // const params = {
      //   pageId: itemObj.link.target,
      //   params: itemObj.link.params,
      //   sessionId: localStorage.getItem("sessionId")
      // };
      // this.appGlobalService.goToForward(params);
      this.pageModalService.openPage(itemObj.link);

    } else if (itemObj.modelType === 'phone') {
      // 电话
      this.phoneArray = itemObj.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), itemObj.label);
      }
    } else if (itemObj.modelType === 'iconSubmit') {
      let submit;
      if (itemObj.button && itemObj.button.submit) {
        submit = itemObj.button.submit;
      } else if (itemObj.submit) {
        submit = itemObj.submit;
      }
      // 领取
      const params = {
        content: submit.content,
        id: submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (itemObj.refresh !== undefined) {
            this.appGlobalService.reloadCurrentPage();
          }
          if (itemObj.link && itemObj.link.target) {
            const pageParams = {
              pageId: itemObj.link.target,
              params: itemObj.link.params ? itemObj.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    } else if (itemObj.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    }
    // 1.7.0 add
    else if (itemObj.modelType === 'question') {
      this.presentQuestion(itemObj, itemObj.msg, dataIndex);
    }
  }

  async presentModal(value, item) {
    console.log("item", item);
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: value,
      component: RemarksContentComponent,
      componentProps: { item, type: value }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData, "moddddddd");
  }

  async presentAction() {
    const buttonsArr = [
      {
        text: "取消",
        cssClass: ["action-sheet-font-color", "action-sheet-font-top"],
        handler: () => {
          actionSheet.dismiss();
        }
      }
    ];
    if (this.phoneArray[1]) {
      buttonsArr.unshift({
        text: this.phoneArray[1],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(Number(this.phoneArray[1]));
        }
      });
    }

    if (this.phoneArray[0]) {
      buttonsArr.unshift({
        text: this.phoneArray[0],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(this.phoneArray[0]);
        }
      });
    }

    const actionSheet = await this.actionSheetCtrl.create({
      mode: "md",
      cssClass: "match-padding",
      buttons: buttonsArr
    });
    await actionSheet.present();
  }

  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }


  async presentQuestion(itemObj, msg, dataIndex) {

    const alert = await this.alertController.create({
      header: '',
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "确定",
          handler: () => {
            let submitParam;
            if (itemObj.submit) {
              submitParam = itemObj.submit;
            } else if (itemObj.button) {
              submitParam = itemObj.button.submit;
            }
            const params = {
              content: submitParam.content,
              id: submitParam.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              this.appGlobalService.showToast(res.message, 1500, "middle");
              if (res.success) {
                if (itemObj.refresh !== undefined) {
                  this.appGlobalService.reloadCurrentPage();
                } else {
                  if (dataIndex >= 0 && dataIndex < this.tagData.data.data.length) {
                    this.tagData.data.data.splice(dataIndex, 1);
                  }
                  if (this.tagData.data.data.length === 0) {
                    //1.7.0 新增
                    this.tagData.data.moreButton = {};
                  }
                }
              }
            });
          }
        }
      ]
    });

    await alert.present();
  }

  async openTipsPageModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: RecommendModalComponent,
            componentProps: { tagData },
            leaveAnimation: ModalFromCenterLeave,
            enterAnimation: ModalFromCenterEnter
          });
          await modal.present();
          const modalData = await modal.onDidDismiss().then((data) => {
            this.appGlobalService.reloadCurrentPage();
          }); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  /**
  *
  * @param item 点击图标
  */
  iconClick(item, dataIndex?) {
    if (dataIndex >= 0) {
      this.dataIndex = dataIndex;
    }
    // this.hiddenInformation();
    // console.log(item);
    if (item.modelType === "pageModal") {
      this.pageModalService.openPage(item.link, '', res => {
        if (res) {
          this.updateItem();
        }
      });
    }
    if (item.modelType === "iconLink") {
      if (item.link.type && (item.link.type === 'chat' || item.link.type === 'submitLink')) {//

        if (item.button !== undefined && item.button.submit !== undefined) {
          item.beforeSubmit = item.button.submit;
        }
        if (item.beforeSubmit) {
          const params = {
            content: item.beforeSubmit.content,
            id: item.beforeSubmit.id,
            sessionId: localStorage.getItem("sessionId")
          };
          this.httpService.post("application/submit", params, res => {
            if (res.success) {
              if (res.data && res.data.eventResult && item.link.params && item.link.params.eventResult) {
                item.link.params[item.link.params.eventResult] = res.data.eventResult;
              }
              if (item.link.type === 'submitLink') {
                this.pageModalService.openPage(item.link);
              } else {
                this.httpService.gotoChat(item, item.link.params.customerUserId);
              }
            } else {
              if (res.message && res.message.length > 0)
                this.appGlobalService.showToast(res.message, 1500, "middle");
            }
          });
        } else {
          this.httpService.gotoChat(item, item.link.params.customerUserId);
        }

      } else if (item.label === '分享') {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.link.params
        };
        this.httpService.post('application/page', params, res => {
          console.log(JSON.parse(res.script));
          const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
          // console.log(tmpShareData);
          this.presentShareModal(tmpShareData);
        });
      } else {
        // // 修改
        // const params = {
        //   pageId: item.link.target,
        //   params: item.link.params,
        //   sessionId: localStorage.getItem("sessionId")
        // };
        // this.appGlobalService.goToForward(params);
        this.pageModalService.openPage(item.link);
      }
    }
    if (item.modelType === "iconSubmit") {
      let submit;
      if (item.button && item.button.submit) {
        submit = item.button.submit;
      } else if (item.submit) {
        submit = item.submit;
      }
      const params = {
        content: submit.content,
        id: submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (submit.content !== undefined && submit.content.btnId !== undefined) {
            const btnId = submit.content.btnId;
            $('#' + btnId).click();
          } else {
            // const tabIndex = parseInt(item.tabClick);
            // if (item.tabClick) {
            //   setTimeout(() => {
            //     this.eventService.eventEmit.emit("topTabChangeByIndex", tabIndex);
            //   }, 1000);
            // }
            if (item.refresh !== undefined) {
              this.appGlobalService.reloadCurrentPage();
            }
            if (item.link && item.link.target) {
              const pageParams = {
                pageId: item.link.target,
                params: item.link.params ? item.link.params : {},
                sessionId: localStorage.getItem("sessionId")
              };
              this.appGlobalService.goToForward(pageParams);
            }
          }

        }
      });
    }

    if (item.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    }
    if (item.modelType === "phone") {
      // 电话
      this.phoneArray = item.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), item.label);
      }
    }
    if (item.modelType === "dialog") {
      // 备注
      // this.remarksIcon = item;
      // this.openRemarks = true;
      this.presentModal("remarks", item);
    }
    // 商铺列表新增类型
    if (item.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", item);
    }
    // 新增两个components类型
    if (item.modelType === "remarkList") {
      // tslint:disable-next-line:max-line-length
      // const moreObj = JSON.parse('{"layout":"right","data":[{"submit":{"id":"refresh","content":{"opportunity_id":"5eb3aed42872fb0001f76ed7"}},"action":"submit","label":"刷新","paramName":"opportunity_id"},{"link":{"type":"page","params":{"opportunity_id":"5eb3aed42872fb0001f76ed7"},"target":144348},"action":"link","label":"修改"}],"icon":"nav_icon_more@3x.png"}');
      if (item.listRemark) {
        this.remarkList(item);
      }
    }
    if (item.modelType === "childIconLink") {
      if (item.childIconList) {
        this.remarkList(item);
      }
    }
    // 1.7.0 新增弹窗
    if (item.modelType === 'question') {
      this.presentQuestion(item, item.msg, dataIndex);
    }

    // 1.6.21 复制按钮
    if (item.modelType === 'copy') {
      this.shareService.copyUrl(item.msg);
    }


  }

  updateItem() {

    const that = this;

    if (!this.tagData.data.data[that.dataIndex].id) {
      return;
    }
    if (that.tagData.data.data[that.dataIndex].updateItemType !== undefined
      && that.tagData.data.data[that.dataIndex].updateItemType === 'delete') {
      that.tagData.data.data.splice(that.dataIndex, 1);
      return;
    }
    const page: any = this.appGlobalService.getCurrentTarget();
    if (page.params) {
    } else {
      page.params = {}
    }
    page.params.id = this.tagData.data.data[that.dataIndex].id;
    this.httpService.post('application/page', page, async res => {
      const tagData = JSON.parse(res.script).views[0].tags;
      tagData.forEach(element => {
        if (element.style === 'appInfoListTag' && element.data && element.data.data[0]) {
          that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[0]);
        }

      });
    });
  }

  // 分享弹框
  async presentShareModal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }



  remarkList(more, dataIndex?) {
    const that = this;
    const buttons: any = [];
    if (more.childIconList) {
      more.listRemark = more.childIconList;
    } else {
      more['listRemark'] = more;
    }
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          // console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.selectItem(more, buttonIndex, undefined, dataIndex);
          }, 200);
        }
      }
    );
  }

  go(item, e) {
    if (e) {
      e.stopPropagation();
    }
    if (item.link && item.link.link && item.link.link.type === 'phone') {
      this.presentAlertConfirm(Number(item.link.link.params.mobile), item.link.link.params.userName);
    } else if (item.link && item.link.link && item.link.link.type === 'chat') {
      this.pageModalService.openPage(item.link.link);
    } else {
      if (item.link.link) {
        this.pageModalService.openPage(item.link.link);
      } else {
        this.pageModalService.openPage(item.link);
      }
    }
  }

  ngOnDestroy(): void {
    this.eventService.removeCustomListListenersByName(this.listenerName);
    // this.eventService.removeCustomListListeners();
  }

  getInterger(value) {
    return parseInt(value, 10);
  }

  careBtn(item) {
    if (item.link) {
      if (item.link.link) {
        this.pageModalService.openPage(item.link.link);
      } else {
        this.pageModalService.openPage(item.link);
      }
    } else {
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        if (res.success) {
          if (res.data && res.data.eventResult !== undefined && res.data.eventResult === 'true') {
            item.state = '1';
            item.label = '已关注';
          } else if (res.data && res.data.eventResult !== undefined && res.data.eventResult === 'false') {
            item.state = '0';
            item.label = '关注';
          }
        }
      });
    }
  }
}
